import $axios from '@/utils/axios';
// import server from './server.config';
import Qs from 'qs';
import {
  Message
} from 'element-ui';
import router from '@/router/index';
/**
 * code为非1000是抛错 可结合自己业务进行修改
 * 
 * **/
const dealResponse = function (response, resolve) {
  let res = response.data;
  if (res.code) {
    if (res.code === 1000 || res.code === 200) {
      resolve(res);
    } else if (res.code === 401) {
      Message({
        type: 'error',
        message: `['尚未登录授权或授权过期，请登录']`
      });
      router.replace({
        path: '/login'
      });
      resolve(res);
    } else {
      Message({
        type: 'error',
        message: `[${res.code},${res.message}]`
      });
      resolve(res);
    }
  } else {
    // 二进制无res.code
    resolve(response);
  }
};

// 封装GET方法
const get = function (url, ...args) {
  return new Promise((resolve, reject) => {
    $axios.get(url, Object.assign({}, ...args)).then(res => {
      dealResponse(res, resolve);
    }).catch(err => {
      reject(err);
    });
  });
};

// 封装POST方法
const post = function (url, data = {}, ...args) {
  return new Promise((resolve, reject) => {
    $axios.post(url, data, ...args).then(res => {
      dealResponse(res, resolve);
    }).catch(err => {
      reject(err);
    });
  });
};

// 封装get请求方法,自动添加参数
const addArrayParamsByGet = function (url, [params, ...args]) {
  let search = Qs.stringify(params, {
    arrayFormat: 'repeat'
  });
  url = url + '?' + search;
  return new Promise((resolve, reject) => {
    $axios.get(url, ...args).then(res => {
      dealResponse(res, resolve);
    }).catch(err => {
      reject(err);
    });
  });
};

// 封装post请求方法,自动添加参数
const addFormDataParamsByPost = (url, [params, ...args]) => {
  let search = Qs.stringify(params, {
    arrayFormat: 'repeat'
  });
  url = url + '?' + search;
  return new Promise((resolve, reject) => {
    $axios.post(url, ...args).then(res => {
      dealResponse(res, resolve);
    }).catch(err => {
      reject(err);
    });
  });
};

export default {
  get,
  post,
  addArrayParamsByGet,
  addFormDataParamsByPost
};
